import 'package:applications/module/home/po/application_po.dart';
import 'package:applications/module/home/home_notifier.dart';
import 'package:applications/module/home/widgets/recommend_item.dart';
import 'package:applications/module/home/widgets/topfree_item.dart';
import 'package:applications/widgets/bar/search_bar.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class HomePage extends ConsumerStatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  ConsumerState<ConsumerStatefulWidget> createState() => _HomePageState();
}

class _HomePageState extends ConsumerState<HomePage> {
  final ScrollController _controller = ScrollController();

  @override
  void initState() {
    super.initState();

    EasyRefresh.defaultHeaderBuilder = () => const ClassicHeader(
          dragText: "下拉刷新",
          readyText: "正在刷新...",
          armedText: "释放刷新",
          processingText: "正在刷新...",
          processedText: "刷新完成",
          failedText: "刷新失败",
          noMoreText: "没有更多数据",
          messageText: "上次更新 %T",
          showMessage: false,
          backgroundColor: Colors.transparent,
          hapticFeedback: true,
        );
    EasyRefresh.defaultFooterBuilder = () => const ClassicFooter(
          dragText: "上拉加载",
          readyText: "正在刷新...",
          armedText: "释放刷新",
          processingText: "正在刷新...",
          processedText: "刷新完成",
          failedText: "刷新失败",
          noMoreText: "没有更多数据",
          messageText: "上次更新 %T",
          showMessage: false,
          backgroundColor: Colors.transparent,
          hapticFeedback: true,
        );
  }

  @override
  Widget build(BuildContext context) {
    debugPrint("重新构建");
    final state = ref.watch(productModelProvider);
    return Scaffold(
      appBar: SearchBar(
        onPressed: (value) {
          if (mounted) {
            if (_controller.positions.isNotEmpty) {
              // _controller.jumpTo(0);
              _controller.animateTo(
                0,
                duration: const Duration(milliseconds: 500),
                curve: Curves.easeIn,
              );
            }
            ref.watch(productModelProvider.notifier).queryByName(value);
          }
        },
      ),
      body: state.when(
        empty: () => const Center(
          child: Text(
            '暂无数据',
            textAlign: TextAlign.center,
            overflow: TextOverflow.ellipsis,
            maxLines: 1,
          ),
        ),
        ready: (data) => _buildContent(context, ref, data),
        error: (String error) {
          debugPrint(error.toString());
          return Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const Padding(
                  padding: EdgeInsets.all(8.0),
                  child: Text("网络异常"),
                ),
                TextButton(
                  child: const Text("点击重试"),
                  onPressed: () {
                    ref.refresh(productModelProvider);
                  },
                ),
              ],
            ),
          );
        },
        loading: () => const Center(child: CupertinoActivityIndicator()),
      ),
    );
  }

  Widget _buildContent(
      BuildContext ctx, WidgetRef ref, List<ApplicationPo> data) {
    var stateNotifier = ref.watch(productModelProvider.notifier);
    return Center(
      child: EasyRefresh(
        // header: const MaterialHeader(),
        controller: stateNotifier.refreshController,
        onRefresh: stateNotifier.refreshData,
        onLoad: stateNotifier.loadMore,
        child: ListView.separated(
          key: const Key('scroller'),
          controller: _controller,
          itemBuilder: (context, index) =>
              _buildTopfreeItem(context, ref, data, index),
          separatorBuilder: (buildContext, index) {
            return const SizedBox.shrink();
          },
          // 此处加1, 是将最受欢迎的app布局同时放到刷新列表中
          itemCount: data.length + 1,
        ),
      ),
    );
  }

  /// 受欢迎的App
  Widget _recommendBuildWidet(BuildContext context) {
    var listTopgrossing =
        ref.watch(productModelProvider.notifier).listTopgrossing;
    if (listTopgrossing.isEmpty) return const SizedBox.shrink();
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 30.w, vertical: 20.w),
          child: Text(
            'Recoment',
            textAlign: TextAlign.left,
            style: TextStyle(fontSize: 32.sp, fontWeight: FontWeight.w500),
          ),
        ),
        EasyRefresh(
          child: SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Padding(
              padding: EdgeInsets.only(
                left: 11.w,
                right: 11.w,
                bottom: 15.w,
              ),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: List.generate(
                  listTopgrossing.length,
                  (index) {
                    var model = listTopgrossing.elementAt(index);
                    return RecommendItem(index: index, model: model);
                  },
                ).toList(),
              ),
            ),
          ),
        ),
        const Divider(height: 0)
      ],
    );
  }

  /// 热门免费应用
  Widget _buildTopfreeItem(BuildContext context, WidgetRef ref,
      List<ApplicationPo> data, int index) {
    String search = ref.watch(productModelProvider.notifier).search;

    /// 此处为最受欢迎App布局, 搜索条件不为空时,不显示最受欢迎App的布局
    if (index == 0) {
      return search == ''
          ? _recommendBuildWidet(context)
          : const SizedBox.shrink();
    }
    var model = data.elementAt(index - 1);
    // 设置ValueKey,避免搜索时列表数据不更新(会导致widget无法重用)
    return RepaintBoundary(
      child: TopfreeItem(key: ValueKey(model.id), index: index, model: model),
    );
  }
}
